<template>
  <div class="medical-advice-view">
    <div class="page-title">医嘱管理</div>
    
    <!-- 筛选区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-select v-model="status" placeholder="医嘱状态">
            <el-option label="全部" value="" />
            <el-option label="已执行" value="executed" />
            <el-option label="未执行" value="pending" />
            <el-option label="已过期" value="expired" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            placeholder="选择日期范围"
          />
        </el-col>
        <el-col :span="6">
          <el-input v-model="searchKey" placeholder="搜索患者姓名/医嘱内容" />
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-col>
        <el-col :span="2">
          <el-button @click="resetFilter">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 医嘱列表 -->
    <el-card class="advice-list-card">
      <el-table
        :data="adviceList"
        border
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="序号" width="80" />
        <el-table-column prop="patientName" label="患者姓名" />
        <el-table-column prop="patientId" label="患者ID" width="120" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="content" label="医嘱内容" :show-overflow-tooltip="true">
          <template #default="scope">
            <div class="advice-content">{{ scope.row.content }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 'pending' ? 'warning' : 
                     scope.row.status === 'executed' ? 'success' : 'danger'"
            >
              {{ scope.row.status === 'pending' ? '未执行' : 
                 scope.row.status === 'executed' ? '已执行' : '已过期' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleViewDetails(scope.row)"
            >
              查看详情
            </el-button>
            <el-button 
              size="small" 
              type="text" 
              @click="handleEditAdvice(scope.row)"
              :disabled="scope.row.status === 'executed' || scope.row.status === 'expired'"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </el-card>

    <!-- 医嘱详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="医嘱详情"
      :width="600"
    >
      <el-card>
        <div class="detail-item">
          <span class="detail-label">患者姓名：</span>
          <span class="detail-value">{{ currentAdvice.patientName || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">患者ID：</span>
          <span class="detail-value">{{ currentAdvice.patientId || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">创建时间：</span>
          <span class="detail-value">{{ currentAdvice.createTime || '-' }}</span>
        </div>
        <div class="detail-item">
          <span class="detail-label">医嘱状态：</span>
          <span class="detail-value">
            <el-tag
              :type="currentAdvice.status === 'pending' ? 'warning' : 
                     currentAdvice.status === 'executed' ? 'success' : 'danger'"
            >
              {{ currentAdvice.status === 'pending' ? '未执行' : 
                 currentAdvice.status === 'executed' ? '已执行' : '已过期' }}
            </el-tag>
          </span>
        </div>
        <div class="detail-item full-width">
          <span class="detail-label">医嘱内容：</span>
          <div class="detail-content">{{ currentAdvice.content || '-' }}</div>
        </div>
        <div class="detail-item" v-if="currentAdvice.executionTime">
          <span class="detail-label">执行时间：</span>
          <span class="detail-value">{{ currentAdvice.executionTime || '-' }}</span>
        </div>
      </el-card>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button 
          type="primary" 
          @click="handleExecuteAdvice"
          v-if="currentAdvice.status === 'pending'"
        >
          标记为已执行
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑医嘱对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑医嘱"
      :width="600"
    >
      <el-form ref="adviceForm" :model="formData" label-width="80px">
        <el-form-item label="医嘱内容：" required>
          <el-input 
            v-model="formData.content" 
            type="textarea" 
            rows="6" 
            placeholder="请输入医嘱内容..." 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEditAdvice">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import axios from 'axios';

// 状态管理
const status = ref('');
const dateRange = ref([]);
const searchKey = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(50);

// 对话框状态
const detailDialogVisible = ref(false);
const editDialogVisible = ref(false);
const currentAdvice = ref({});
const formData = reactive({
  content: ''
});

// 模拟医嘱数据
const adviceList = ref([
  {
    id: 1,
    patientName: '张三',
    patientId: 'PT20230512001',
    createTime: '2023-05-12 09:30',
    content: '1. 注意休息，避免剧烈运动；2. 按时服药，每日三次，每次一片；3. 多饮水，饮食清淡；4. 三天后复查。',
    status: 'pending'
  },
  {
    id: 2,
    patientName: '李四',
    patientId: 'PT20230512002',
    createTime: '2023-05-12 10:15',
    content: '1. 卧床休息，减少活动；2. 遵医嘱服用止痛药；3. 避免辛辣刺激性食物；4. 如症状加重，立即复诊。',
    status: 'executed',
    executionTime: '2023-05-12 14:20'
  },
  {
    id: 3,
    patientName: '王五',
    patientId: 'PT20230511005',
    createTime: '2023-05-11 15:40',
    content: '1. 坚持每日测量血压并记录；2. 保持情绪稳定，避免激动；3. 定期复诊，每月一次。',
    status: 'pending'
  },
  {
    id: 4,
    patientName: '赵六',
    patientId: 'PT20230510012',
    createTime: '2023-05-10 11:20',
    content: '1. 术后伤口保持清洁干燥；2. 避免提重物；3. 七天后拆线；4. 如有红肿发热，及时就诊。',
    status: 'expired'
  },
  {
    id: 5,
    patientName: '钱七',
    patientId: 'PT20230512008',
    createTime: '2023-05-12 14:10',
    content: '1. 注意保暖，避免受凉；2. 多饮温水，每日不少于2000ml；3. 清淡饮食，忌油腻生冷。',
    status: 'pending'
  }
]);

// 搜索方法
const handleSearch = () => {
  console.log('搜索条件:', { 
    status: status.value, 
    dateRange: dateRange.value, 
    searchKey: searchKey.value 
  });
  currentPage.value = 1;
  // 实际应用中这里会调用API进行搜索
};

// 重置筛选条件
const resetFilter = () => {
  status.value = '';
  dateRange.value = [];
  searchKey.value = '';
  currentPage.value = 1;
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 行点击事件
const handleRowClick = (row) => {
  handleViewDetails(row);
};

// 查看详情
const handleViewDetails = (row) => {
  currentAdvice.value = { ...row };
  detailDialogVisible.value = true;
};

// 编辑医嘱
const handleEditAdvice = (row) => {
  currentAdvice.value = { ...row };
  formData.content = row.content;
  editDialogVisible.value = true;
};

// 保存编辑
const saveEditAdvice = () => {
  // 模拟API请求保存编辑
  axios.put(`/api/medical-advice/${currentAdvice.value.id}`, {
    content: formData.content
  }).then(response => {
    console.log('医嘱更新成功', response.data);
    // 更新列表中的数据
    const index = adviceList.value.findIndex(item => item.id === currentAdvice.value.id);
    if (index !== -1) {
      adviceList.value[index].content = formData.content;
    }
    editDialogVisible.value = false;
  }).catch(error => {
    console.error('医嘱更新失败', error);
  });
};

// 标记为已执行
const handleExecuteAdvice = () => {
  // 模拟API请求
  axios.post(`/api/medical-advice/${currentAdvice.value.id}/execute`, {
    executionTime: new Date().toLocaleString()
  }).then(response => {
    console.log('医嘱标记为已执行', response.data);
    // 更新列表中的数据
    const index = adviceList.value.findIndex(item => item.id === currentAdvice.value.id);
    if (index !== -1) {
      adviceList.value[index].status = 'executed';
      adviceList.value[index].executionTime = new Date().toLocaleString();
    }
    currentAdvice.value.status = 'executed';
    currentAdvice.value.executionTime = new Date().toLocaleString();
  }).catch(error => {
    console.error('操作失败', error);
  });
};
</script>

<style scoped>
.medical-advice-view {
  padding: 20px;
}

.page-title {
  font-size: 20px;
  font-weight: 500;
  margin-bottom: 20px;
  color: #1e293b;
}

.filter-card {
  margin-bottom: 20px;
  padding: 15px;
}

.advice-list-card {
  padding: 0;
}

.pagination {
  margin-top: 15px;
  text-align: right;
  padding: 0 15px 15px;
}

.advice-content {
  max-width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.detail-item {
  margin-bottom: 15px;
  display: flex;
  align-items: flex-start;
}

.detail-label {
  color: #64748b;
  width: 100px;
  flex-shrink: 0;
}

.detail-value {
  flex-grow: 1;
  font-weight: 500;
}

.full-width {
  width: 100%;
}

.detail-content {
  flex-grow: 1;
  font-weight: 500;
  white-space: pre-line;
  background-color: #f8fafc;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #e2e8f0;
}
</style>
    